
import 'dart:async';

import 'package:eq/native/constants.dart';
import 'package:eq/src/core.dart';
import 'package:eq/src/interpreter.dart';
import 'package:eq/src/statement.dart';
import 'package:eq/src/utils.dart';
///
///定时器模块
///
///定时执行任务
///

void addTimerFunctions(Module module) {
  addNativeFunction("periodic", _periodic, module);
  addNativeFunction("cancel", _cancel, module);
  addNativeFunction("isActive", _isActive, module);
  addNativeFunction("getTick", _getTick, module);
}

///1.函数
///2.定时时间
Value _periodic(List<Value> args) {
  int days = 0;
  int hours = 0;
  int minutes = 0;
  int seconds = 0;
  int milliseconds = 0;
  int microseconds = 0;
  StatementResult result;
  int i = 0;

  for (i; i < args.length; i++) {
    if (i == 0 && args[0].type == ValueType.FUNCTION_VALUE) {
    } else if (args[i].type == ValueType.INT_VALUE ||
        args[i].type == ValueType.DOUBLE_VALUE) {
      if (i == 1) {
        microseconds = args[i].value.toInt();
      } else if (i == 2) {
        milliseconds = args[i].value.toInt();
      } else if (i == 3) {
        seconds = args[i].value.toInt();
      } else if (i == 4) {
        minutes = args[i].value.toInt();
      } else if (i == 5) {
        hours = args[i].value.toInt();
      } else if (i == 6) {
        days = args[i].value.toInt();
      } else {
        break;
      }
    } else {
      return Value(ValueType.NULL_VALUE, null);
    }
  }

  Timer timer = Timer.periodic(
      Duration(
        days: days,
        hours: hours,
        minutes: minutes,
        seconds: seconds,
        milliseconds: milliseconds,
        microseconds: microseconds,
      ), (e) {
    List<Value> t1 = [
      Value(ValueType.BOOLEAN_VALUE, e.isActive),
      Value(ValueType.INT_VALUE, e.tick)
    ];

    result =
        functionCallbyName(args[0].path ?? args[0].module, args[0].value, t1);
    if (result.type == StatementResultType.ERROR_RUNTIME_RESULT) {
      exitApp(result.error!, 1);
    }
  });

  return Value(ValueType.NATIVE_POINTER_VALUE, timer, module: eq_timer);
}

Value _cancel(List<Value> args) {
  if (args.isNotEmpty && args[0].type == ValueType.NATIVE_POINTER_VALUE) {
    Timer timer = args[0].value;
    if (timer.isActive) {
      timer.cancel();
    }
  }

  return Value(ValueType.NULL_VALUE, null);
}

Value _isActive(List<Value> args) {
  if (args.isNotEmpty && args[0].type == ValueType.NATIVE_POINTER_VALUE) {
    Timer timer = args[0].value;
    return Value(ValueType.BOOLEAN_VALUE, timer.isActive);
  }

  return Value(ValueType.NULL_VALUE, null);
}

Value _getTick(List<Value> args) {
  if (args.isNotEmpty && args[0].type == ValueType.NATIVE_POINTER_VALUE) {
    Timer timer = args[0].value;
    return Value(ValueType.INT_VALUE, timer.tick);
  }

  return Value(ValueType.NULL_VALUE, null);
}
